<?php

require_once("Spreadsheet/Excel/Writer.php");

class ExcelOutput implements RegistryObject, ReportOutput {

	public function setup() {
	}

	public function getTitle() {
		return "excel";
	}

	public function write($reportObj, $outputfile = null) {

		$reportTitle = $reportObj->getTitle();

		// Create an instance
		$xls =& new Spreadsheet_Excel_Writer();

		// Send HTTP headers to tell the browser what's coming
		$xls->send(filenameSafe($reportTitle) . ".xls");

		// Add a worksheet to the file, returning an object to add data to
		$sheet =& $xls->addWorksheet($reportTitle);


		//Initial cell
		$row = 0;
		$col = 0;

		//Report title
		$sheet->writeString($row, $col, $reportTitle);
		$row++;
		$row++;


		$dom = $reportObj->getDOM();
		$qresults = $dom->getElementsByTagName("query-result");
		for ($i=0; $i<$qresults->length; $i++) {
			$qresult 	= $qresults->item($i);
			$qresultTitle 	= $qresult->getAttribute("title");

			//Query result title
			$sheet->writeString($row, $col, $qresultTitle);
			$row++;

			$dataRows = $qresult->getElementsByTagName("row");
			for ($d=0; $d<$dataRows->length; $d++) {

				$col = 0;

				$values = $dataRows->item($d)->getElementsByTagName("label");
				for ($p=0; $p<$values->length; $p++) {
					$sheet->writeString($row, $col, trim($values->item($p)->firstChild->nodeValue));
					$col++;
				}

				$values = $dataRows->item($d)->getElementsByTagName("p");
				for ($p=0; $p<$values->length; $p++) {
					$sheet->writeString($row, $col, trim($values->item($p)->firstChild->nodeValue));
					$col++;
				}

				$row++;
			}
		}


		// Finish the spreadsheet, dumping it to the browser
		$xls->close();
	}

}

Registry::register("output", new ExcelOutput());

?>